import axios from "axios";

import {
  handleRequestHeader as handleChangeRequestHeader,
  handleAuth as handleConfigureAuth,
  handleAuthError,
  handleGeneralError,
  handleNetworkError,
} from "./tools";

type Fn = (data: FcResponse<any>) => unknown;

interface IAnyObj {
  [index: string]: unknown;
}

interface FcResponse<T> {
  resCode: string;
  message: string;
  data: T;
}
const instance = axios.create({
  baseURL: "/api/",
  timeout: 5000,
});

// 请求拦截
instance.interceptors.request.use((config) => {
  config = handleChangeRequestHeader(config);
  config = handleConfigureAuth(config);
  return config;
});

// 响应拦截
instance.interceptors.response.use(
  (response) => {
    if (response.status !== 200) return Promise.reject(response.data);
    handleAuthError(response.data.errno);
    handleGeneralError(response.data.errno, response.data.errmsg);
    return response;
  },
  (err) => {
    handleNetworkError(err.response.status);
    Promise.reject(err.response);
  }
);
export default abstract class api {
  static async get<T>(
    url: string,
    params: IAnyObj = {},
    clearFn?: Fn
  ): Promise<[any, FcResponse<T> | undefined]> {
    return new Promise((resolve) => {
      instance
        .get(url, { params })
        .then((result) => {
          let res: FcResponse<T>;
          if (clearFn !== undefined) {
            res = clearFn(result.data) as unknown as FcResponse<T>;
          } else {
            res = result.data as FcResponse<T>;
          }
          resolve([null, res as FcResponse<T>]);
        })
        .catch((err) => {
          resolve([err, undefined]);
        });
    });
  }
  static async post<T>(
    url: string,
    data: IAnyObj,
    params: IAnyObj = {}
  ): Promise<[any, FcResponse<T> | undefined]> {
    return new Promise((resolve) => {
      instance
        .post(url, data, { params })
        .then((result) => {
          resolve([null, result.data as FcResponse<T>]);
        })
        .catch((err) => {
          resolve([err, undefined]);
        });
    });
  }
}
